/**
 * 入口文件
 * by blue
 * 功能：初始化及声明控制器，初始化数据模型,初始化界面写入body，执行判断socket类型模块，公开对外接口，显示im加载
 */
fangimjs.define("main", ["jquery", "event/event", "controller/totalController", "sdk/judgeSocket", "setting/setting"], function (require) {
    "use strict";
    var $ = require("jquery"),
        vars = fangimjs.data.vars,
        loadFlag = false;//加载完成标志
    var win = window;

    // 加载css
    function loadCss(url) {
        var doc = win.document;
        var head = doc.head || doc.getElementsByTagName('head')[0] || doc.documentElement;
        var baseElement = head.getElementsByTagName('base')[0];
        var node = doc.createElement('link');

        node.charset = 'utf-8';
        node.rel = 'stylesheet';
        node.href = url;
        baseElement ? head.insertBefore(node, baseElement) : head.appendChild(node);
    }

    var base = fangimjs.data.base;
    base = base.substr(0, base.length - 1);
    base = base.substr(0, base.lastIndexOf('/') + 1);
    fangimjs.data.base = base;
    loadCss(base + 'style/nsftalk2.0.1.css');

    var chatBox = $('<div class="fbbox"></div>');
    $(win.document.body).append(chatBox).append('<div id="swfContainer"></div>');
    var innerHtml = '' +
    '<div class="fbconl notmove" id="chatW_l" style="display:none;">' +
        '<div class="fbconltit clearfix" id="chatW_L_DX">' +
            '<div class="flol">' +
                '<a id="im_shop_url" style="display:none;">' +
                    '<div class="flol im_head"><div class="im_head_img"></div><span class="im_status"></span></div>' +
                '</a>' +
                '<div class="flol im_name"></div>' +
                '<span class="flol im_status" style="display:none;"></span>' +
            '</div>' +
            '<div class="flor">' +
                '<span class="im_tel"></span>' +
                '<i id="chatW_l_close"><a href="javascript:void(0);"><img src="' + base + 'images/icon-close.png" width="12" height="12" /></a></i>' +
            '</div>' +
        '</div>' +
        '<div class="fbconlcon">' +
            '<div class="fbcon"><ul id="chatW_l_msg"></ul></div>' +
            '<p id="chatW_l_alert"><span></span></p>' +
        '</div>' +
        '<div class="fbtools clearfix">' +
            '<div class="sl">' +
                '<i id="chatW_l_btn_face" class="im_face">' +
                '</i>' +
                '<i class="no2">' +
                    '<form id="chatW_l_pic" enctype="multipart/form-data" action="" method="post" target="">' +
                    '</form>' +
                '</i>' +
                '<div id="chatW_l_face" class="biaoqi" style="display:none;">' +
                    '<div class="contnr">' +
                    '<div class="bqcon"></div>' +
                    '</div>' +
                '</div>' +
            '</div>' +
            '<div class="sr" id="chatW_l_his"><a href="javascript:void(0);">消息记录</a></div>' +
        '</div>' +
        '<div class="textarea">' +
            '<textarea id="chatW_l_text"></textarea>' +
        '</div>' +
        '<div class="fbbutr clearfix" id="chatW_l_send">' +
            '<div class="sl"><a href="http://client.3g.fang.com/http/wap/index.html" target="_blank">下载房天下APP，消息随时随地看！</a></div>' +
            '<div class="sl" style="text-decoration:none; color:#333;">\u6309 Enter \u63d0\u4ea4</div>' +
            '<div class="sr"><a href="javascript:void(0);" class="fbbut01" id="chatW_l_btn_send">发送</a></div>' +
        '</div>' +
    '</div>' +
    '<div class="fbconr" id="chatW_rt" style="display:none;">' +
        '<div class="fbconrtit im_title">' +
            '<a class="flor iconmin" href="javascript:void(0);" id="chatW_rt_min"></a>' +
            '<a class="flor iconclose" href="javascript:void(0);" id="chatW_rt_close" style="display:none;"></a>' +
            '<span class="im_online">在线</span>' +
        '</div>' +
        '<div class="listcon">' +
            '<div class="conscroll">' +
                '<div id="chatW_rt_contact"></div>' +
                '<div id="chatW_rt_contact_2"></div>' +
                '<div id="chatW_rt_contact_3"></div>' +
                '<div id="chatW_rt_contact_4"></div>' +
            '</div>' +
            '<div class="im_onlineTime" style="display: none;">客服在线时间：(不在线可留言)<br>每天 早9:00~晚5:30</div>' +
        '</div>' +
        '<div class="btnOnline"><em></em>' +
        '\u8054\u7cfb\u4eba [ <span>0</span>/<span>0</span> ]' +
        '</div>' +
    '</div>' +
    '<div class="btnServiceUp" id="chatW_service" style="display: none;">购房在线咨询</div>' +
    '<div class="btnMessage black0" id="chatW_newAlert" style="display: none;"><a href="javascript:;">\u60a8\u6709<span class="bold im_num" id="chatW_min_num">0</span>\u6761\u672a\u8bfb\u6d88\u606f</a></div>' +
    '<div class="btnPhone" id="chatW_worldPhone" style="display: none;">购房热线电话<br>400-890-8753</div>' +
    '<div class="blue_alertCon" id="alertCon" style="display: none;"></div>' +
    '<div class="btnOnlineTalkUp" id="chatW_onlineTalk" style="display:none;">' +
        '<div class="btnContactUp"><em></em>' +
        '\u8054\u7cfb\u4eba [ <span id="chatW_rb_num1">0</span>/<span id="chatW_rb_num2">0</span> ]' +
        '</div>'+
    '</div>';
    chatBox.get(0).innerHTML = (innerHtml);

    vars.chatBox = chatBox;
    // 右侧联系人容器
    vars.chatBoxMain = chatBox.find("#chatW_rt");
    // 最小化在线数量容器 .btnOnlineTalkUp
    // vars.chatBoxBar = chatBox.find("#chatW_rb");
    // 最小化“购房在线咨询”容器 .btnServiceUp
    // vars.worldChatBoxBar = chatBox.find("#worldChatBtn");、
    vars.btnServiceUp = chatBox.find("#chatW_service");
    vars.btnOnlineTalkUp = chatBox.find("#chatW_onlineTalk");
    // 左侧消息容器
    vars.chatBoxDetail = chatBox.find("#chatW_l");
    // 新消息提醒容器
    vars.chatBoxNewMsg = chatBox.find("#chatW_newAlert");
    // 最小化容器左侧购房热线容器
    vars.chatBoxPhone = chatBox.find("#chatW_worldPhone");
    // 右侧联系人容器中客服在线时间信息元素
    vars.onlineTimeCon = chatBox.find(".im_onlineTime");

    var lStorage = win.localStorage;
    try {
        lStorage && lStorage.setItem("testPrivateModel", !1);
    } catch (d) {
        lStorage = null
    }
    vars.localStorage = lStorage;
    // 表情解析变量
    vars.emojis = function() {
        var emojisList = ['微笑', '撇嘴', '色', '发呆', '得意', '流泪', '害羞', '闭嘴', '睡', '大哭', '尴尬', '发怒', '调皮', '呲牙', '惊讶', '难过', '酷', '冷汗', '抓狂', '吐', '偷笑', '愉快', '白眼', '傲慢', '饥饿', '困', '惊恐', '流汗', '憨笑', '悠闲', '奋斗', '咒骂', '疑问', '嘘', '晕', '疯了', '哀', '骷髅', '敲打', '再见', '擦汗', '抠鼻', '鼓掌', '糗大了', '坏笑', '左哼哼', '右哼哼', '哈欠', '鄙视', '委屈', '快哭了', '阴险', '亲亲', '吓', '可怜', '菜刀', '西瓜', '啤酒', '篮球', '乒乓', '咖啡', '饭', '猪头', '玫瑰', '凋谢', '嘴唇', '爱心', '心碎', '蛋糕', '闪电', '炸弹', '刀', '足球', '瓢虫', '便便', '月亮', '太阳', '礼物', '拥抱', '强', '弱', '握手', '胜利', '抱拳', '勾引', '拳头', '差劲', '爱你', 'NO', 'OK', '爱情', '飞吻', '跳跳', '发抖', '怄火', '转圈', '磕头', '回头', '跳绳', '投降', '激动', '街舞', '献吻', '左太极', '右太极'];
        // var emojisList = ['\u5fae\u7b11', '\u6487\u5634', '\u8272', '\u53d1\u5446', '\u5f97\u610f', '\u6d41\u6cea', '\u5bb3\u7f9e', '\u95ed\u5634', '\u7761', '\u5927\u54ed', '\u5c34\u5c2c', '\u53d1\u6012', '\u8c03\u76ae', '\u5472\u7259', '\u60ca\u8bb6', '\u96be\u8fc7', '\u9177', '\u51b7\u6c57', '\u6293\u72c2', '\u5410', '\u5077\u7b11', '\u6109\u5feb', '\u767d\u773c', '\u50b2\u6162', '\u9965\u997f', '\u56f0', '\u60ca\u6050', '\u6d41\u6c57', '\u61a8\u7b11', '\u60a0\u95f2', '\u594b\u6597', '\u5492\u9a82', '\u7591\u95ee', '\u5618', '\u6655', '\u75af\u4e86', '\u54c0', '\u9ab7\u9ac5', '\u6572\u6253', '\u518d\u89c1', '\u64e6\u6c57', '\u62a0\u9f3b', '\u9f13\u638c', '\u7cd7\u5927\u4e86', '\u574f\u7b11', '\u5de6\u54fc\u54fc', '\u53f3\u54fc\u54fc', '\u54c8\u6b20', '\u9119\u89c6', '\u59d4\u5c48', '\u5feb\u54ed\u4e86', '\u9634\u9669', '\u4eb2\u4eb2', '\u5413', '\u53ef\u601c', '\u83dc\u5200', '\u897f\u74dc', '\u5564\u9152', '\u7bee\u7403', '\u4e52\u4e53', '\u5496\u5561', '\u996d', '\u732a\u5934', '\u73ab\u7470', '\u51cb\u8c22', '\u5634\u5507', '\u7231\u5fc3', '\u5fc3\u788e', '\u86cb\u7cd5', '\u95ea\u7535', '\u70b8\u5f39', '\u5200', '\u8db3\u7403', '\u74e2\u866b', '\u4fbf\u4fbf', '\u6708\u4eae', '\u592a\u9633', '\u793c\u7269', '\u62e5\u62b1', '\u5f3a', '\u5f31', '\u63e1\u624b', '\u80dc\u5229', '\u62b1\u62f3', '\u52fe\u5f15', '\u62f3\u5934', '\u5dee\u52b2', '\u7231\u4f60', '\u004e\u004f', '\u004f\u004b', '\u7231\u60c5', '\u98de\u543b', '\u8df3\u8df3', '\u53d1\u6296', '\u6004\u706b', '\u8f6c\u5708', '\u78d5\u5934', '\u56de\u5934', '\u8df3\u7ef3', '\u6295\u964d', '\u6fc0\u52a8', '\u8857\u821e', '\u732e\u543b', '\u5de6\u592a\u6781', '\u53f3\u592a\u6781'];
        var emojisMap = {};
        for (var i = 0; i < emojisList.length; i++) {
            emojisMap[emojisList[i]] = 'emoji_' + (i + 1001 + '').substr(1) + '.png';
        }
        return emojisMap;
    }();

    var totalController = require("controller/totalController"),//引入总控制器
        event = require("event/event"),//引入事件类
        setting = require("setting/setting").getInstance();//初始化配置信息
    totalController.init();//初始化总控制器


    // 初始化 config 为初始化时参数
    if (vars.config.hidden) {
        event.trigger("view:window:change", setting.WINDOW_STATUS_CLOSE);
    }
    /*对外接口暂定*/

    win.fangWebIM = win.fangWebIM || {};

    /**
     * 因为目前新房使用 im 时用 shop 替代的 loupan 字段，为了统一
     * 兼容函数，逐步将 shop 字段替换掉
     * @return {[type]} [description]
     */
    function loupanToShop(data){
        if ($.isArray(data)) {
            for (var i = data.length - 1; i >= 0; i--) {
                if (data[i] && data[i].loupan){
                    data[i].shop = data[i].loupan;
                }
            }
        } else if (data && data.loupan){
            data.shop = data.loupan
        }
        return data;
    };

    /**
     * 打开聊天窗口（即添加联系人得操作）
     * @param data
     */
    win.fangWebIM.openChat = function (data) {
        // data = loupanToShop(data);
        if (loadFlag) {
            event.trigger("view:contacts:add", data);
        }
    };
    /**
     * 添加经纪人
     * @param data
     */
    win.fangWebIM.addBroker = function (data) {
        // data = loupanToShop(data);
        if (data && $.isArray(data)) {
            vars.broker = data;
            if (loadFlag) {
                event.trigger("view:otherContacts:add", {type: setting.CONTACT_BROKER, data: data});
            }
        }
    };
    /**
     * 添加置业顾问
     * @param data
     */
    win.fangWebIM.addConsultant = function (data) {
        // data = loupanToShop(data);
        if (data && $.isArray(data)) {
            vars.consultant = data;
            if (loadFlag) {
                event.trigger("view:otherContacts:add", {type: setting.CONTACT_CONSULTANT, data: data});
            }
        }
    };
    /**
     * 添加客服
     * @param data
     */
    win.fangWebIM.addCustomerService = function (data) {
        // data = loupanToShop(data);
        if (data && $.isArray(data)) {
            vars.customerService = data;
            if (loadFlag) {
                event.trigger("view:otherContacts:add", {type: setting.CUSTOMER_SERVICE, data: data});
            }
        }
    };
    /**
     * 打开联系人列表窗口
     */
    win.fangWebIM.open = function () {
        vars.config.hidden = false;
        totalController.open();
    };

    /**
     * 暴露登出方法
     */
    win.fangWebIM.logout = function () {
        event.trigger('socket:userstate:logout');
    };

    /**
     * 暴露登入方法
     */
    win.fangWebIM.login = function () {
        event.trigger('view:socket:login', true);
    };

    /**
     * 绑定socket选择事件，接收完成后则开始执行socket相关操作
     */
    event.on("socket:select", function (t) {
        loadFlag = true;
        //$("#loader").remove();
        totalController.setSocket(t);
        if (vars.hasOwnProperty("broker") && vars.broker) {
            win.fangWebIM.addBroker(vars.broker);
        }
        if (vars.hasOwnProperty("consultant") && vars.consultant) {
            win.fangWebIM.addConsultant(vars.consultant);
        }
        if (vars.hasOwnProperty("customerService") && vars.customerService) {
            win.fangWebIM.addCustomerService(vars.customerService);
        }
    });
    require("sdk/judgeSocket")();//执行判断使用的socket方式函数
});
